package com.konghao.test.junit.dao;

import com.konghao.test.junit.model.User;
import com.konghao.test.junit.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * UserDaoImpl--JunitTest
 *
 * @author: Jovi
 * @createTime: 2017-09-27 16:55
 **/
public class UserDaoImpl implements UserDao {

    @Override
    public void add(User user) {

        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DbUtil.getConnection();
            String sql = "insert into t_user(username,nickname,password) value (?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getNickame());
            ps.setString(3,user.getPassword());

            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                DbUtil.close(ps);
                DbUtil.close(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void delete(String username) {

        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DbUtil.getConnection();
            String sql = "DELETE FROM t_user WHERE username = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);

            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                DbUtil.close(ps);
                DbUtil.close(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public User load(String username) {

        User u = null;

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DbUtil.getConnection();
            String sql = "SELECT * FROM t_user WHERE username = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            rs = ps.executeQuery();

            while (rs.next()) {
                if (u == null) {
                    u = new User();
                }
                u.setId(rs.getInt("id"));
                u.setNickame(rs.getString("nickname"));
                u.setUsername(rs.getString("username"));
                u.setPassword(rs.getString("password"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                DbUtil.close(rs);
                DbUtil.close(ps);
                DbUtil.close(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return u;
    }
}
